/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.yixiang.co
* 注意：
* 本软件为www.yixiang.co开发研制，未经购买不得使用
* 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
* 一经发现盗用、分享等行为，将追究法律责任，后果自负
*/
package co.yixiang.modules.auction.rest;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.api.ApiResult;
import co.yixiang.api.YshopException;
import co.yixiang.dozer.service.IGenerator;
import co.yixiang.logging.aop.log.Log;
import co.yixiang.modules.auction.domain.AuctionProduct;
import co.yixiang.modules.auction.domain.AuctionProductD;
import co.yixiang.modules.auction.service.AuctionProductService;
import co.yixiang.modules.auction.service.YxAuctionRecordService;
import co.yixiang.modules.auction.service.dto.AuctionProductDto;
import co.yixiang.modules.auction.service.dto.AuctionProductQueryCriteria;
import co.yixiang.modules.auction.service.dto.YxAuctionRecordDto;
import co.yixiang.modules.auction.service.mapper.AuctionProductMapper;
import co.yixiang.utils.RedisUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import net.sf.json.JSONObject;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
* @author yhh
* @date 2021-02-18
*/
@AllArgsConstructor
@Api(tags = "拍卖商品管理")
@RestController
@RequestMapping("/api/AuctionProduct")
public class AuctionProductController {

    private final AuctionProductService AuctionProductService;
    private final AuctionProductMapper auctionProductMapper;
    private final IGenerator generator;
    private final RedisUtils redisUtils;
    private final YxAuctionRecordService yxAuctionRecordService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
//    @PreAuthorize("@el.check('admin','AuctionProduct:list')")
    public void download(HttpServletResponse response, AuctionProductQueryCriteria criteria) throws IOException {
        AuctionProductService.download(generator.convert(AuctionProductService.queryAll(criteria), AuctionProductDto.class), response);
    }

    @GetMapping
    @Log("查询拍卖商品")
    @ApiOperation("查询拍卖商品")
//    @PreAuthorize("@el.check('admin','AuctionProduct:list')")
    public ResponseEntity<Object> getAuctionProducts(AuctionProductQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(AuctionProductService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增拍卖商品")
    @ApiOperation("新增拍卖商品")
//    @PreAuthorize("@el.check('admin','AuctionProduct:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody AuctionProduct resources){
        AuctionProductService.save(resources);
        //塞入redis中
        AuctionProductD product = auctionProductMapper.getProduct(resources.getId());
        redisUtils.set("product" + resources.getId(), JSONObject.fromObject(product).toString());
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改拍卖商品")
    @ApiOperation("修改拍卖商品")
//    @PreAuthorize("@el.check('admin','AuctionProduct:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody AuctionProduct resources){
        AuctionProductService.updateById(resources);
        //塞入redis中
        AuctionProductD product = auctionProductMapper.getProduct(resources.getId());
        redisUtils.set("product" + resources.getId(), JSONObject.fromObject(product).toString());
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除拍卖商品")
    @ApiOperation("删除拍卖商品")
//    @PreAuthorize("@el.check('admin','AuctionProduct:del')")
    @DeleteMapping
    public ResponseEntity<Object> deleteAll(@RequestBody Long[] ids) {
        Arrays.asList(ids).forEach(id->{
            AuctionProduct auctionProduct = AuctionProductService.getById(id);
            auctionProduct.setIsDel(1);
            AuctionProductService.updateById(auctionProduct);
        });
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 根据timeId查询抢拍商品列表
     */
    @GetMapping("/list/{timeId}")
    @ApiOperation(value = "根据timeId查询抢拍商品列表", notes = "根据timeId查询抢拍商品列表")
    public ApiResult getYxAuctionProductPageList(@PathVariable String timeId,
                                                 @RequestParam(value = "isBuy",required = false)Integer isBuy,
                                                 @RequestParam(value = "page",defaultValue = "1") int page,
                                                 @RequestParam(value = "limit",defaultValue = "10") int limit){
        if (StrUtil.isBlank(timeId) || !NumberUtil.isNumber(timeId)){
            throw new YshopException("参数错误");
        }
//        Page<YxAuctionRecordDto> yxAuctionProductPageList=new Page<>();
//        if((null ==searchName || "".equals(searchName)) && Long.valueOf(0)!= Long.valueOf(timeId)){
//            Object o = redisUtil.get("time"+Long.valueOf(timeId)+"&page"+page);
//            if(ObjectUtil.isEmpty(o)) return ApiResult.ok(yxAuctionProductPageList);
//            com.alibaba.fastjson.JSONObject pList = com.alibaba.fastjson.JSONObject.parseObject(o.toString());
//            pList.put("pages" , pList.getInteger("total")/30 + (pList.getInteger("total")%30 == 0 ? 0 : 1));
//            return ApiResult.ok(pList);
//        }
        return ApiResult.ok(yxAuctionRecordService.getYxAuctionProductPageLists(page, limit,isBuy, Long.valueOf(timeId)));
    }
}
